package cn.tianyigps.tainyigpsdatahandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Created with IDEA
 *
 * @description: 接口调用
 * @author: cui.guibin
 * @create: 2019/3/20 17:51
 **/
@Component
@Slf4j
public class Rest {

    @Autowired
    private RestTemplate restTemplate;

    private static final ObjectMapper OM = new ObjectMapper();
    public void sendData(Map<String,Object> params){


        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        String string = null;
        try {
            string = OM.writeValueAsString(params);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        log.info("向PHP推送数据,入参:{}",string);
        HttpEntity<String> entity = new HttpEntity<>(string,headers);
        String s = null;
        try {
            String callbackUrl = (String) params.get("callback");
            if(!callbackUrl.startsWith("http")){
                callbackUrl = "http://" + callbackUrl;
            }
            s = restTemplate.postForObject(callbackUrl, entity, String.class);
            log.info("向PHP推送数据,返回:{}",s);
        } catch (RestClientException e) {
            log.error("设备信息推送失败!");
            log.error(e.getMessage());
            e.printStackTrace();
        }

    }

}
